/**
 * Created by admin on 2018/1/23.
 */
layui.config({
    base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        $ = layui.jquery;
    $(".show_all").click(function(){
        $.ajax({
            url : "boat/surveryQuery",
            type : "get",
            dataType : "json",
            success : function(data){
                boatData = data;
                if(window.sessionStorage.getItem("addBoat")){
                    var addBoat = window.sessionStorage.getItem("addBoat");
                    boatData = JSON.parse(addBoat).concat(boatData);
                }
                //执行加载数据的方法
                boatList();
            }
        })
    }) 
    //加载页面数据
    var boatData = '';
    $.ajax({
        url : "boat/surveryQuery",
        type : "get",
        dataType : "json",
        success : function(data){
            boatData = data;
            if(window.sessionStorage.getItem("addBoat")){
                var addBoat = window.sessionStorage.getItem("addBoat");
                boatData = JSON.parse(addBoat).concat(boatData);
            }
            //执行加载数据的方法
            boatList();
        }
    })

    //全文查询
    $(".search_btn").click(function(){
        var newArray = [];
        if($(".search_input").val() != ''){
        	var search_input = $(".search_input").val();
            var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
                $.ajax({
                    url : "boat/globalQuery?search_input="+search_input,
                    type : "get",
                    dataType : "json",
                    success : function(data){
                        if(window.sessionStorage.getItem("addBoat")){
                            var addBoat = window.sessionStorage.getItem("addBoat");
                            boatData = JSON.parse(addBoat).concat(data);
                        }else{
                            boatData = data;
                        }
                        for(var i=0;i<boatData.length;i++){
                            var boatStr = boatData[i];
                            var selectStr = $(".search_input").val();
                            function changeStr(data){
                                var dataStr = '';
                                var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
                                if(showNum > 1){
                                    for (var j=0;j<showNum;j++) {
                                        dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
                                    }
                                    dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
                                    return dataStr;
                                }else{
                                    dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
                                    return dataStr;
                                }
                            }
                            //船舶ID
                            if(boatStr.boatId.indexOf(selectStr) > -1){
                                boatStr["boatId"] = changeStr(boatStr.boatId);
                            }
                            //船舶名称
                            if(boatStr.boatName.indexOf(selectStr) > -1){
                                boatStr["boatName"] = changeStr(boatStr.boatName);
                            }
                            //船舶类型
                            if(boatStr.boatKind.indexOf(selectStr) > -1){
                                boatStr["boatKind"] = changeStr(boatStr.boatKind);
                            }

                            if(boatStr.boatId.indexOf(selectStr)>-1 || boatStr.boatName.indexOf(selectStr)>-1 || boatStr.boatKind.indexOf(selectStr)>-1 || boatStr.boatName.indexOf(selectStr)>-1 || boatStr.boatWriter.indexOf(selectStr)>-1 ){
                                newArray.push(boatStr);
                            }
                        }
                        boatData = newArray;
                        boatList(boatData);
                    }
                })

                layer.close(index);
            },2000);
        }else{
            layer.msg("请输入需要查询的内容");
        }
    })

    //添加船舶
    $(".boatAdd_btn").click(function(){
        var index = layui.layer.open({
            title : "添加船舶",
            type : 2,
            content : "boatAdd",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
    })
    
    //高级查询
    $(".advanced_search").click(function(){
        var newArray = [];
        if($(".boatId").val() != '' || $(".boatName").val() != '' || $(".boatKind").val() != ''
        	|| $(".boatWriter").val() != ''){
        	var params = {};
        	params.boatId = $(".boatId").val();
        	params.boatName = $(".boatName").val();
        	params.boatKind = $(".boatKind").val();
        	params.boatWriter = $(".boatWriter").val();
        	var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
                $.ajax({
                    url : "boat/advancedQuery",
                    type : "get",
                    data : params,
                    dataType : "json",
                    success : function(data){
                        if(window.sessionStorage.getItem("addBoat")){
                            var addBoat = window.sessionStorage.getItem("addBoat");
                            boatData = JSON.parse(addBoat).concat(data);
                        }else{
                            boatData = data;
                        }
                        for(var i=0;i<boatData.length;i++){
                            var boatStr = boatData[i];
                            var selectStr = $(".search_input").val();
                            function changeStr(data){
                                var dataStr = '';
                                var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
                                if(showNum > 1){
                                    for (var j=0;j<showNum;j++) {
                                        dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
                                    }
                                    dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
                                    return dataStr;
                                }else{
                                    dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
                                    return dataStr;
                                }
                            }
//                            //船舶ID
//                            if(boatStr.boatId.indexOf(selectStr) > -1){
//                                boatStr["boatId"] = changeStr(boatStr.boatId);
//                            }
//                            //船舶名称
//                            if(boatStr.boatName.indexOf(selectStr) > -1){
//                                boatStr["boatName"] = changeStr(boatStr.boatName);
//                            }
//                            //船舶类型
//                            if(boatStr.boatKind.indexOf(selectStr) > -1){
//                                boatStr["boatKind"] = changeStr(boatStr.boatKind);
//                            }
//
                            if(boatStr.boatId.indexOf(selectStr)>-1 || boatStr.boatKind.indexOf(selectStr)>-1 || boatStr.boatName.indexOf(selectStr)>-1 || boatStr.boatWriter.indexOf(selectStr)>-1 ){
                                newArray.push(boatStr);
                            }
                        }
                        boatData = newArray;
                        boatList(boatData);
                    }
                })

                layer.close(index);
            },2000);
        }else{
            layer.msg("请输入需要查询的内容");
        }
    })
        	
    //批量删除
    $(".batchDel").click(function(){
        var $checkbox = $('.boat_list tbody input[type="checkbox"][name="checked"]');
        var $checked = $('.boat_list tbody input[type="checkbox"][name="checked"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                setTimeout(function(){
                    //删除数据
                    for(var j=0;j<$checked.length;j++){
                        for(var i=0;i<boatData.length;i++){
                            if(boatData[i].boatId == $checked.eq(j).parents("tr").find(".boat_del").attr("data-id")){
                            	$.ajax({
                            		url : "boat/delete?boatId="+boatData[i].boatId,
                            		type : "post"
                            	})
                                boatData.splice(i,1);
                                boatList(boatData);
                            }
                        }
                    }
                    $('.boat_list thead input[type="checkbox"]').prop("checked",false);
                    form.render();
                    layer.close(index);
                    layer.msg("删除成功");
                },2000);
            })
        }else{
            layer.msg("请选择需要删除的文章");
        }
    })

    //全选
    form.on('checkbox(allChoose)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断信息是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
        data.elem.checked;
        if(childChecked.length == child.length){
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
        }else{
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
        }
        form.render('checkbox');
    })

    //操作


    $("body").on("click",".boat_del",function(){  //删除
        var _this = $(this);
        layer.confirm('确定删除此信息？',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();
            for(var i=0;i<boatData.length;i++){
                if(boatData[i].boatId == _this.attr("data-id")){
                	$.ajax({
                		url : "boat/delete?boatId="+boatData[i].boatId,
                		type : "post"
                	})
                    boatData.splice(i,1);
                    boatList(boatData);
                }
            }
            layer.close(index);
        });
    })

    function boatList(that){
    	var authorites = [];
        $.ajax({
        	url : "user/authorites",
        	async:false,
        	success : function(data){
        		for(var i=0;i<data.length;i++){
        			authorites.push(data[i].authority);
        		}
        	}
        })
        //渲染数据
        function renderDate(data,curr){
            var dataHtml = '';
            if(!that){
                currData = boatData.concat().splice(curr*nums-nums, nums);
            }else{
                currData = that.concat().splice(curr*nums-nums, nums);
            }
            if(currData.length != 0){
                for(var i=0;i<currData.length;i++){
                	if(authorites.indexOf("ROLE_ADMIN")>-1 || authorites.indexOf("ROLE_INPUT")>-1){
                    dataHtml += '<tr>'
                        +'<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
                        +'<td>'+currData[i].boatId+'</td>'
                        +'<td>'+currData[i].boatName+'</td>'
                        +'<td>'+currData[i].boatKind+'</td>'
                        +'<td>'+currData[i].boatWriter+'</td>'
                        +'<td>'
                        +  '<a class="layui-btn  layui-btn-mini layui-btn-normal news_detail" href="boatSurveryInfo?boatId='+currData[i].boatId+'"><i class="layui-icon">&#xe611;</i> 详情</a>'
                        +  '<a class="layui-btn layui-btn-mini boat_edit" href="boatSurveryRevise?boatId='+currData[i].boatId+'"><i class="iconfont icon-edit"></i> 编辑</a>'
                        +  '<a class="layui-btn layui-btn-danger layui-btn-mini boat_del" data-id="'+data[i].boatId+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
                        +'</td>'
                        +'</tr>';
                	}else{
                		 dataHtml += '<tr>'
                             +'<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
                             +'<td>'+currData[i].boatId+'</td>'
                             +'<td>'+currData[i].boatName+'</td>'
                             +'<td>'+currData[i].boatKind+'</td>'
                             +'<td>'+currData[i].boatWriter+'</td>'
                             +'<td>'
                             +  '<a class="layui-btn  layui-btn-mini layui-btn-normal news_detail" href="boatSurveryInfo?boatId='+currData[i].boatId+'"><i class="layui-icon">&#xe611;</i> 详情</a>'
                             +'</td>'
                             +'</tr>';
                	}
                    
                }
            }else{
                dataHtml = '<tr><td colspan="5" style="text-align: center">暂无数据</td></tr>';
            }
            return dataHtml;
        }

        //分页
        var nums = 5; //每页出现的数据量
        if(that){
            boatData = that;
        }
        laypage({
            cont : "page",
            skip:true,
            pages : Math.ceil(boatData.length/nums),
            jump : function(obj,first){
                $(".boat_content").html(renderDate(boatData,obj.curr));
                $('.boat_list thead input[type="checkbox"]').prop("checked",false);
                form.render();
                if(!first){
                    layer.msg('第'+obj.curr+'页');
                }
            }
        })
    }
})